using UnityEngine;
using UnityEngine.UI;

public class FinalSwordPanel : BasePanel
{
    [Header("CD")]
    public float timer = 5;
    public float stopTimer = 5;
    [Header("生成剑的方向")]
    public string dir = "";
    [Header("CdUI")]
    public Image cdUI;
    [Header("攻击按钮")]
    public Button attackButton;

    //守塔人魔血量
    public Text hpText;
    public int hp = 15;

    //守塔人
    public TowerMan towerMan;
    public override void OnClose()
    {
        base.OnClose();
        EventManager.ReMsgDic("MsgFinalHurt", DamageMsg);
    }

    public override void OnInit()
    {
        base.OnInit();
        path="UI/Panel/FinalSwordPanel";
        type=PanelType.Panel;

        //拯救了公主
        if (GameManager.Instance.isSavePro) hp = 10;

        EventManager.AddMsgDic("MsgFinalHurt", DamageMsg);
    }

    public override void OnShow(params object[] par)
    {
        base.OnShow(par);

        cdUI=item.transform.Find("Attack/Cd").GetComponent<Image>();
        hpText=item.transform.Find("Hp/Num").GetComponent<Text>();
        attackButton = item.transform.Find("Attack").GetComponent<Button>();
        attackButton.onClick.AddListener(Attack);

        //方向获取
        dir=(string)par[0];
        towerMan=GameManager.Instance.towerMan.GetComponent<TowerMan>();
        hpText.text = hp.ToString();
        //扣血
        BeHurt(0);
    }
    private void Update()
    {
        UpdateTimer();
    }

    //cd计算
    public void UpdateTimer()
    {
        if(timer<stopTimer)
        {
            timer+=Time.deltaTime;
            cdUI.fillAmount=timer/(stopTimer*1f);
        }
    }
    //进行攻击一次
    public void Attack()
    {
        if (timer<stopTimer) return;

        //生成剑从主角身上
        GameObject newObj = Instantiate(PoolManager.Instance.swordObj);
        newObj.transform.position=GameManager.Instance.player.transform.position;
        Vector2 currDir = Vector2.zero;
        if(dir=="上")
        {
            currDir=Vector2.up;
        }
        else if(dir=="下")
        {
            currDir=-Vector2.up;
        }
        else if(dir=="左")
        {
            currDir=-Vector2.right;
        }
        else if(dir=="右")
        {
            currDir=Vector2.right;
        }
        newObj.transform.right=currDir;
        newObj.GetComponent<FinalSwordObj>().SetDir(currDir);
        //进入cd
        timer=0;
        AudManager.instance.PlayUIAud(AudManager.instance.uiDic["添加单词"], 1f);
    }
    //伤害消息
    public void DamageMsg(MsgBase msgBase)
    {
        MsgFinalHurt msg = (MsgFinalHurt)msgBase;

        BeHurt(msg.amount);
    }
    //扣血
    public void BeHurt(int amount)
    {
        hp-=amount;
        hpText.text=hp.ToString();

        //当血量低于1时触发剧情杀
        if(hp<=0)
        {
            towerMan.OverBattle();
            Close();
        }
    }
}
public class MsgFinalHurt:MsgBase
{
    public MsgFinalHurt() { proName="MsgFinalHurt"; }

    public int amount = 1;
}
